//
//  DynamicHeightTextView.swift
//  LeTu
//
//  Created by gy on 2023/12/8.
//

import UIKit

class DynamicHeightTextView: UITextView, UITextViewDelegate {

    /// 字数限制
    var limitCount = 0
    /// 提示文字
    var placeholder: String = "" {
        didSet {
            placeHolderLabel.text = placeholder
        }
    }
    override var font: UIFont? {
        willSet {
            placeHolderLabel.font = newValue
        }
    }
    private var minHight: CGFloat?

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        delegate = self
        
        textContainerInset = UIEdgeInsets(top: 0, left: -self.textContainer.lineFragmentPadding, bottom: 0, right:  -self.textContainer.lineFragmentPadding)
        textContainer?.lineFragmentPadding = 0
        configUI()
        
    }

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "\n" {
            textView.resignFirstResponder()
            return false
        }
        return true
    }
    
    func textViewDidChange(_ textView: UITextView) {
        
        if limitCount != 0 {
            textView.text = Utils.clipTextViewTextLength(textView: textView, limitNum: limitCount)
        }
        
        placeHolderLabel.isHidden = textView.text.count > 0
        
        if minHight == nil {
            minHight = self.height
        }
        
        snp.updateConstraints { make in
            make.height.equalTo(max(minHight ?? self.height, textView.text.heightWithLimit(width: self.width-self.textContainer.lineFragmentPadding*2, font: self.font ?? kSetPingFangRegular(16))))
        }
        
    }

    // MARK: - configUI
    func configUI() {
        
        addSubview(placeHolderLabel)
        
        placeHolderLabel.snp.makeConstraints { make in
            make.height.equalToSuperview()
            make.left.equalTo(self.textContainer.lineFragmentPadding)
        }
        
    }
    private var placeHolderLabel: UILabel = {
        let placeHolderLabel = UILabel()
        placeHolderLabel.font = kSetPingFangRegular(14)
        placeHolderLabel.textColor = .app_textGrayColor
        return placeHolderLabel
    }()
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
}


